package com.handycraftz.site.server.beans;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.handycraftz.site.shared.util.HandyCraftzConstants;

public class MailerDaemon
{
	
	@SuppressWarnings("finally")
	public synchronized static boolean sendMail(String mailSenderName, String mailSubject,String mailBody, String mailSender, String mailRecipient) 
	{
		boolean mailingStatus = false;
		try
		{
			Properties props = new Properties();
			props.setProperty("mail.transport.protocol", "smtp");
			props.setProperty("mail.host", HandyCraftzConstants.HANDYCRAFTZ_MAILER_HOST);
			props.put("mail.smtp.auth", "true");
			props.put("mail.smtp.port", HandyCraftzConstants.HANDYCRAFTZ_MAILER_PORT);
			props.put("mail.smtp.socketFactory.port", HandyCraftzConstants.HANDYCRAFTZ_MAILER_PORT);
			props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.socketFactory.fallback", "false");
			props.setProperty("mail.smtp.quitwait", "false");
			Session session = Session.getDefaultInstance(props,	new javax.mail.Authenticator() 
			{
				protected PasswordAuthentication getPasswordAuthentication() 
				{
					return new PasswordAuthentication
					(HandyCraftzConstants.HANDYCRAFTZ_MAILER_USERNAME,HandyCraftzConstants.HANDYCRAFTZ_MAILER_PASSWORD);
				}
			});
			MimeMessage message = new MimeMessage(session);
			message.setSender(new InternetAddress(HandyCraftzConstants.HANDYCRAFTZ_MAILER_USERNAME));
			message.setSubject(mailSubject);
			message.setContent(MessageFormatter.createContactMessage(mailSender, mailSenderName, mailBody), HandyCraftzConstants.HANDYCRAFTZ_MAILER_MIME_TYPE);
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailRecipient));
			Transport.send(message);
			mailingStatus = true;
		} 
		catch (Exception e) 
		{
			mailingStatus = false;
			e.printStackTrace();
		}
		finally
		{
			return mailingStatus;
		}
	}
	
	
}
